package com.mankiw.insight.spring.web;

import com.mankiw.insight.spring.Component;
import com.mankiw.insight.spring.sub.Autowried;
import com.mankiw.insight.spring.sub.PostConstruct;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.bridge.SLF4JBridgeHandler;

import java.io.File;
import java.io.IOException;
import java.util.logging.LogManager;

@Component
public class TomcatServer {

    @Autowried
    private DispatcherServlet dispatcherServlet;

    @PostConstruct
    public void start() throws Exception {
        //日志格式转换
        LogManager.getLogManager().reset();
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        int port = 8080;
        Tomcat tomcat = new Tomcat();//创建tomcat对象
        tomcat.setPort(port);//绑定端口
        tomcat.getConnector();

        String contextPath = "";
        String docBase = new File(".").getAbsolutePath();
        Context context = tomcat.addContext(contextPath, docBase);//创建context上下文，这个上下文是和文件夹有关的
        //向tomcat中添加一个servlet对象
        //HttpServlet对象
        tomcat.addServlet(contextPath,"dispatcherServlet", dispatcherServlet);
        //helloservlet到底处理什么样的请求
        context.addServletMappingDecoded("/*","dispatcherServlet");
        tomcat.start();
        System.out.println("tomcat started port:" + port);
    }
}
